package com.guotd.jspwork2.controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import static com.guotd.jspwork2.utils.JDBCUtil.getConnection;

@WebServlet("/login")
public class checkLoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id=request.getParameter("id");
        String password=request.getParameter("password");
            try (Connection con = getConnection()) {
                String sql = "select * from user where ID=? and PASSWORD=?";
                try (PreparedStatement pstmt = con.prepareStatement(sql)) {
                    pstmt.setString(1, id);
                    pstmt.setString(2, password);
                    ResultSet rs = pstmt.executeQuery();
                    if (rs.next()) {
                        request.getSession().setAttribute("username", id);
                        response.sendRedirect("getAllKinds");
                    } else {
                        request.setAttribute("error", "用户名或密码错误");
                        request.getRequestDispatcher("login.jsp").forward(request, response);
                    }
                }
            }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}